import { Component, Vue, Prop } from 'vue-property-decorator';
import * as CommonService from '@/views/common/common-service';

@Component({})
export default class SearchItem extends Vue {
  @Prop({
    required: false,
    default: () => { },
  }) search!: any

  created() {
    this.init();
  }

  init() {
    if (this.search.type === 'dropdown' && (!this.search.items || this.search.items.length === 0)) {
      if ((this.search.extendSql === null || this.search.extendSql === '') && (this.search.api !== null && this.search.api !== '')) {
        let api = this.getParams(this.search.api, '');
        CommonService.getDate(api, null).then((data: any[]) => {
          let item = [];
          if (data.length > 1) {
            item.push({
              children: null,
              disabled: false,
              icon: null,
              isLeaf: false,
              label: '全部',
              leaf: false,
              level: 0,
              styleClass: null,
              title: null,
              value: ''
            });
          }
          data.forEach(j => {
            item.push({
              children: null,
              disabled: false,
              icon: null,
              isLeaf: false,
              label: j.label,
              leaf: false,
              level: 0,
              styleClass: null,
              title: null,
              value: j.value
            });
          });
          this.search.items = item;
          this.search.value = item[0] ? item[0].value : '';
        });
      }
    }
  }

  getParams(url: string, param: any) {
    let result;
    let reg = /\#(.+?)\#/g;
    while ((result = reg.exec(url)) != null) {
      url = url.replace(result[0], param !== null ? param : '');
    }
    return url;
  }

  onChange(value: any) {
    let resultValue = JSON.parse(JSON.stringify(value));
    if (this.search.type === 'calendar') {
      let [start, end] = value;
      start.set({ hour: 0, minute: 0, second: 0, millisecond: 0 });
      end.set({ hour: 23, minute: 59, second: 59, millisecond: 59 });
      value = [start, end];
    }
    this.$emit('onChange', this.search, resultValue)
  }
}